package com.lemon.service;

import com.alibaba.fastjson.JSONObject;
import com.lemon.entity.Computer;
import com.lemon.utils.GetHardwareDataUtil;
import com.lemon.utils.HttpClientUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static com.lemon.constant.Constant.*;

public class SendDataThread implements Runnable {
    private static final Logger log = LoggerFactory.getLogger(SendDataThread.class);

    private static volatile boolean isRun = true;

    private static long lastUpdataTime = 0L;

    private static final long UPDATA_INTERVAL = 30*1000;

    @Override
    public void run() {
        GetHardwareDataUtil util = GetHardwareDataUtil.getUtil();
        lastUpdataTime = System.currentTimeMillis() - UPDATA_INTERVAL;
        // 循环发送数据 使用http协议
        try {
            while (isRun) {
                if (System.currentTimeMillis() - lastUpdataTime > UPDATA_INTERVAL) {
                    Computer computer = util.getComputer();
                    String data = JSONObject.toJSONString(computer);
                    String token = System.getProperty("apm.token");
                    // 半分钟一次
                    String response = HttpClientUtil.doPost(serviceAdd, data, token);
                    lastUpdataTime += UPDATA_INTERVAL;
                    log.info("send data success.{}", response);
                } else {
                    // 休眠一秒
                    Thread.sleep(1000);
                }
            }
        } catch (Exception e){
            log.error("发生错误, jvm进程已停止", e);
            System.exit(1);
        }
    }

    /**
     *  结束循环
     */
    public static void close(){
        isRun = false;
    }
}
